#include "client.hpp"

Client::Client()
{
    localCertificate = "client-crt.pem";
    privateKey = "client-key.pem";

    start("127.0.0.1", 45434);
    
    logged = false;
}

Client::Client(QString server, quint16 port)
{
    start(server, port);
}

Client::~Client()
{
}

void Client::start(QString server, quint16 port)
{
    // Load private key
    QFile file(privateKey);
    if( !file.open(QIODevice::ReadOnly))
    {
        qDebug() << "Unable to open client private key : " << privateKey;
        return;
    }

    // Passphrase : DefiQt
    QSslKey key(&file, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, "DefiQt");
    file.close();
    client.setPrivateKey(key);

    // Load client's certificate
    client.setLocalCertificate(localCertificate);

    // Load certificate
    if(!client.addCaCertificates( "../ca/ca.pem" ) )
    {
         qDebug() << "Unable to open CA certificate :" << "../ca/ca.pem";
         exit(1);
    }

    // Dont verify server identity
    client.setPeerVerifyMode(QSslSocket::VerifyNone);

    client.ignoreSslErrors();
    connect(&client, SIGNAL(encrypted()), this, SLOT(connection()));
    connect(&client, SIGNAL(readyRead()), this, SLOT(read()));
    client.connectToHostEncrypted(server, port);
}

void Client::connection()
{

}

void Client::buttonConnection(QString id, QString pass)
{
    name = id;
    // Sends password and ID to the server like id:pass
    client.write(QString("login:" + id + ":" + pass).toUtf8());
}

void Client::buttonEcg()
{
	qDebug() << "Boutton ECG !";

	// Sends the command
	client.write(QString("ecg:ecg.txt").toUtf8());
}


void Client::read()
{
	QStringList package;
	QString data = client.readAll();
	package = data.split(":");

	QString command = package[0];
	package.removeFirst();

	if(command == "login")
	{
		PackageManager::login(package,this);
	}

	if(command == "ecg")
	{
		PackageManager::ecg(package, &client);
	}
}

void Client::fnAuthentificationOK()
{
	logged = true;
	emit authentificationOK();
}

void Client::emitAuthentificationFail() { emit authentificationFail(); }
void Client::emitAuthentificationDouble() { emit authentificationDouble(); }
void Client::emitAuthentificationOK() { fnAuthentificationOK(); }
